﻿namespace Arms.Presentation.Web.Areas.People.Controllers
{
    using Arms.Application.Modules.Security;
    using Arms.Framework;
    using Arms.Framework.Validators;
    using Arms.Presentation.Web.Areas.People.Models;
    using Arms.Presentation.Web.Controllers;
    using Newtonsoft.Json;
    using System.Web.Mvc;
    using System.Web.Security;

    public class AuthenticationController : BaseController
    {
        private readonly IMembershipService _membershipService;
        private readonly IFormsService _formsService;
        public AuthenticationController(IMembershipService membershipService, IFormsService formsService)
        {
            _membershipService = Validation.Ensure(membershipService);
            _formsService = Validation.Ensure(formsService);
        }

        [HttpGet]
        [AllowAnonymous]
        public ActionResult Login()
        {
            return View(new LoginModel());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnURL)
        {
            if (ModelState.IsValid)
            {
                var result = model.IsPin ? _membershipService.Authenticate(model.Pin.ToLong()) : _membershipService.Authenticate(model.UserName, model.Password);
                if (result != null && result.IsAuthenticated)
                {
                    string userData = JsonConvert.SerializeObject(_membershipService.GetArmsUserData(result));
                    var authCookie = _formsService.CreateUserAuthHttpCookie(result.UserName, userData, model.RememberMe);
                    base.Response.SetCookie(authCookie);
                    if (!string.IsNullOrEmpty(returnURL))
                    {
                        return Redirect(returnURL);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Dashboard", "");
                    }
                }
                else
                {
                    ModelState.AddModelError("", result.ErrorMessage);
                }
            }
            else
            {
                ModelState.AddModelError("", "Username / password incorrect");
            }

            return View(model);
        }

        [HttpGet]
        [AllowAnonymous]
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Login", "Authentication", "People");
        }
    }
}
